﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace AUV5.Web.Pages
{
    public partial class LoginColorBox : PageBaseFrontend
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
            }
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            //验证登录的错误次数
            string ip = Request.UserHostAddress;
            if (BLL.UserInfoBLL.Instance.FaildLoginLog(ip, false) >= 5)
            {
                errorMessage.InnerHtml = "您已经多次输入密码错误, 请15分钟后再登录";
            }
            else
            {
                Model.UserInfo user = BLL.UserInfoBLL.Instance.Login(txtLoginName.Text.Trim(), base.EncryptMD5(txtPsw.Text.Trim()));

                if (user != null)
                {
                    if (user.IsDel == (int)Common.Enum.auvDel.Del)
                    {
                        errorMessage.InnerHtml = "用户已被禁用！";
                    }
                    else
                    {
                        base.VerifiedInfo = new AUV5.Model.VerifiedInfo(user);
                        if (ckbSave.Checked)
                        {
                            CreateCookie(user);
                        }
                        base.CloseThickBox(true);
                    }
                }
                else
                {
                    int count = BLL.UserInfoBLL.Instance.FaildLoginLog(ip, true);
                    if (count >= 5)
                    {
                        errorMessage.InnerHtml = "您已经输入密码5次错误, 请15分钟后再试";
                    }
                    else
                    {
                        errorMessage.InnerHtml = string.Format("密码第{0}次错误, 您最多有5次机会重试", count);
                    }
                }
            }
            if (errorMessage.InnerHtml != "")
            {
                errorMessage.Visible = true;
            }
        }

        /// <summary>
        /// 创建Cookie存储：用户编号，用户名，用户密码8-16位，密钥
        /// </summary>
        /// <param name="user"></param>
        void CreateCookie(Model.UserInfo user)
        {
            string userId = user.UserID;
            string userName = user.UserName;
            string password = user.Password.Substring(7, 8);
            string secret = System.Configuration.ConfigurationManager.AppSettings["cookie-secret"];
            string finnalSecret = base.EncryptMD5(userId + userName + password + secret).Substring(7, 8);

            CreateCookiesByKeyName("UserCookie", "UserID", userId);
            CreateCookiesByKeyName("UserCookie", "UserName", userName);
            CreateCookiesByKeyName("UserCookie", "Password", password);
            CreateCookiesByKeyName("UserCookie", "Secret", finnalSecret);
        }
    }
}